<template>
  <div id="pictureManagePage">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/picture/addPicture">+ 创建图片</a-button>
        <a-button type="primary" href="/picture/batch" ghost>+ 批量创建图片</a-button>
      </a-space>
    </a-flex>

    <!--    搜索表单-->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从名称和简介搜索"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="类型" name="category">
        <a-input
          :options="categoryOptions"
          v-model:value="searchParams.category"
          placeholder="请输入类型"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          :options="tagOptions"
          v-model:value="searchParams.tags"
          mode="tags"
          placeholder="请输入标签"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PIC_REVIEW_STATUS_OPTIONS"
          placeholder="请输入审核状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>

    <div style="margin-bottom: 16px" />
    <!--    信息表单-->
    <a-table
      :loading="loading"
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="80" />
        </template>
        <template v-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in record.tags || '[]'" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'review'">
          <div>审核状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核时间： {{ dayjs(record.createTime).format('YYYY-MM-DD') }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
              type="link"
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
            >
              通过
            </a-button>
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
              type="link"
              danger
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
            >
              拒绝
            </a-button>
            <a-button type="link" :href="`/picture/addPicture?id=${record.id}`">编辑 </a-button>
            <a-button type="link" danger @click="doDelete(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import {
  allListPictureTagCategoryUsingGet,
  deletePictureUsingPost,
  doPictureReviewUsingPost, listPictureByPageUsingPost,
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost
} from "@/api/pictureController.ts";
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS,
} from '../../constants/picture.ts'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
  },
  {
    title: '审核信息',
    dataIndex: 'review',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

//数据
const dataList = ref<API.PictureVO[]>([])
const total = ref<any>(0)
const tagOptions = ref<String[]>([])
const categoryOptions = ref<String[]>([])
const loading=ref(false)

//搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 5,
  sortField: 'createTime',
  sortOrder: 'descend',
})
// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: String) => `共 ${total} 条`,
  }
})

//获取数据
const fetchData = async () => {
  loading.value=true
  const res = await listPictureByPageUsingPost({
    nullSpaceId: true,
    ...searchParams,
  })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    console.log(dataList.value)
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value=false
}
//获取分类和标签选项
const getTagCateGoryOptions = async () => {
  const res = await allListPictureTagCategoryUsingGet()
  try {
    if (res.data.code === 0 && res.data.data) {
      //原数据为json，需要转换为下拉式接受格式 value  label
      tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
      categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
    } else {
      message.error('加载选项失败：' + res.data.message)
    }
  } catch (e) {
    message.error('加载选项失败：' + e)
  }
}
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}
// 删除数据
const doDelete = async (id: string) => {
  loading.value=true
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败' + res.data.message)
  }
  loading.value=false
}

// 审核数据
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '人工过审' : '拒绝过审'
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  const result = res.data
  if (result.code === 0) {
    message.success('审核操作成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('审核操作成功' + result.message)
  }
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

//页面加载时请求一次
onMounted(() => {
  fetchData()
})
onMounted(() => {
  getTagCateGoryOptions()
})
</script>
<style scoped>
#pictureManagePage {
  max-width: 1600px;
  margin: 0 auto;
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

/* 标题区域 */
.a-flex[justify='space-between'] {
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

h2 {
  margin: 0;
  font-size: 24px;
  color: #1f1f1f;
  font-weight: 600;
}

/* 搜索表单 */
.a-form {
  margin: 24px 0;
  background: #fafafa;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.a-form-item {
  margin-right: 32px;
  margin-bottom: 0;
}

.a-form-item :deep(.ant-form-item-label) {
  min-width: 60px;
  text-align: right;
}

/* 表格样式 */
.a-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.a-table :deep(th) {
  background: #fafafa !important;
  font-weight: 600;
  color: #1f1f1f;
}

.a-table :deep(td) {
  transition: background 0.3s;
}

.a-table :deep(.ant-table-row:hover td) {
  background: #fafafa !important;
}

/* 图片列 */
.a-image {
  display: block;
  margin: 0 auto;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.a-image:hover {
  transform: scale(1.05);
}

/* 标签样式 */
.a-tag {
  margin: 2px 4px;
  border-radius: 12px;
  background: #f0f0f0;
  color: #666;
}

/* 操作按钮 */
.a-button[type='link'] {
  padding: 0 8px;
  color: #1890ff;
}

.a-button[type='link'][danger] {
  color: #ff4d4f;
}

/* 信息展示区域 */
div[data-index='picInfo'],
div[data-index='review'] {
  line-height: 1.6;
  color: #666;
}

/* 时间列 */
.a-table :deep(.ant-table-cell) > .dayjs-format {
  color: #8c8c8c;
  font-size: 13px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  #pictureManagePage {
    padding: 12px;
  }

  .a-form {
    padding: 16px;
  }

  .a-form-item {
    margin-right: 16px;
  }
}
</style>
